﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevAwesome.WebDataBridge.StorageProviders;

namespace DevAwesome.WebDataBridge {

    public class EndPoint {

        public EndPoint( Bridge bridge, IWebDataBridgeStorageProvider storageProvider, Func<object> getDataFunc ) {
            this.Bridge = bridge;
            this.StorageProvider = storageProvider;
            this.GetData = getDataFunc;
        }

        public IWebDataBridgeStorageProvider StorageProvider { get; set; }

        public Bridge Bridge { get; set; }

        public string EndPointName { get; set; }

        public string Description { get; set; }

        private string BridgeKey { get { return string.Format( "{0}/{1}", Bridge.BridgeId, EndPointName ); } }

        public object RetrieveData( ) {
            return RetrieveData<object>( );
        }

        public T RetrieveData<T>( ) where T : class {

            if( StorageProvider.Exists( BridgeKey ) )
                return StorageProvider.Read<T>( BridgeKey );
            else {
                var result = GetData( );
                StorageProvider.Update( BridgeKey, result );
                return result as T;
            }

        }

        private Func<object> GetData { get; set; }

        internal void Refresh( ) {
            StorageProvider.Update( BridgeKey, GetData( ) );
        }
    }
}
